<template>
  <div class="app-edit-page">
    <div class="page-header">
      <a-page-header title="编辑应用信息" :sub-title="appInfo.appName" @back="handleBack" />
    </div>

    <div class="edit-content">
      <a-card title="基本信息" class="edit-card">
        <a-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          layout="vertical"
          @finish="handleSubmit"
        >
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="应用名称" name="appName">
                <a-input
                  v-model:value="formData.appName"
                  placeholder="请输入应用名称"
                  :maxlength="50"
                  show-count
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="代码类型" name="codeGenType">
                <a-input v-model:value="formData.codeGenType" disabled placeholder="代码类型" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="应用封面" name="cover">
            <div class="cover-upload">
              <div class="cover-preview">
                <img
                  v-if="formData.cover"
                  :src="formData.cover"
                  :alt="formData.appName"
                  class="cover-image"
                />
                <div v-else class="cover-placeholder">
                  <PictureOutlined />
                  <p>暂无封面</p>
                </div>
              </div>
              <div class="cover-input">
                <a-input v-model:value="formData.cover" placeholder="请输入封面图片URL" />
                <a-button type="primary" style="margin-top: 8px" @click="handleUploadCover">
                  <UploadOutlined />
                  上传封面
                </a-button>
              </div>
            </div>
          </a-form-item>

          <a-form-item label="初始提示词" name="initPrompt">
            <a-textarea
              v-model:value="formData.initPrompt"
              placeholder="请输入初始提示词"
              :rows="4"
              :maxlength="1000"
              show-count
              disabled
            />
          </a-form-item>

          <!-- 管理员可以编辑优先级 -->
          <a-form-item v-if="isAdmin" label="优先级" name="priority">
            <a-input-number
              v-model:value="formData.priority"
              :min="0"
              :max="999"
              placeholder="请输入优先级"
              style="width: 100%"
            />
            <div class="form-help">优先级为100的应用将显示在精选列表中</div>
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="submitting">
                <SaveOutlined />
                保存修改
              </a-button>
              <a-button @click="handleBack">
                <ArrowLeftOutlined />
                返回
              </a-button>
              <a-button v-if="isAdmin" type="default" @click="handleDelete" danger>
                <DeleteOutlined />
                删除应用
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 应用统计信息 -->
      <a-card title="应用统计" class="edit-card">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-statistic title="创建时间" :value="formatTime(appInfo.createTime)" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="最后编辑" :value="formatTime(appInfo.editTime)" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="部署时间" :value="formatTime(appInfo.deployedTime)" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="优先级" :value="appInfo.priority" />
          </a-col>
        </a-row>
      </a-card>

      <!-- 用户信息 -->
      <a-card title="创建者信息" class="edit-card" v-if="appInfo.user">
        <div class="user-info">
          <a-avatar :src="appInfo.user.userAvatar" :size="64" />
          <div class="user-details">
            <h4>{{ appInfo.user.userName || '未设置昵称' }}</h4>
            <p>{{ appInfo.user.userAccount }}</p>
            <p>{{ appInfo.user.email }}</p>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 上传封面弹窗 -->
    <a-modal
      v-model:open="uploadModalVisible"
      title="上传封面"
      @ok="handleUploadSubmit"
      @cancel="handleUploadCancel"
      :confirm-loading="uploading"
    >
      <a-upload
        v-model:file-list="fileList"
        name="image"
        list-type="picture-card"
        class="cover-uploader"
        :show-upload-list="false"
        :before-upload="beforeUpload"
        @change="handleUploadChange"
      >
        <div v-if="imageUrl">
          <img :src="imageUrl" alt="cover" style="width: 100%" />
        </div>
        <div v-else>
          <PlusOutlined />
          <div style="margin-top: 8px">上传</div>
        </div>
      </a-upload>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  SaveOutlined,
  ArrowLeftOutlined,
  DeleteOutlined,
  PictureOutlined,
  UploadOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { getAppById1, updateApp1 } from '@/api/yingyongjiekou'
import { getAppById, updateApp, deleteApp } from '@/api/guanliyuanjiekou'
import { uploadImage } from '@/api/tongyongjiekou'

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

const appId = computed(() => route.params.appId as string)

// 是否为管理员
const isAdmin = computed(() => loginUserStore.loginUser.userRole === 'admin')

// 权限检查
const canEdit = computed(() => {
  return isAdmin.value || loginUserStore.loginUser.id === appInfo.userId
})

// 应用信息
const appInfo = reactive<API.AppVO>({})

// 表单数据
const formData = reactive({
  appName: '',
  cover: '',
  initPrompt: '',
  codeGenType: '',
  priority: 0
})

// 表单验证规则
const formRules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 2, max: 50, message: '应用名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  cover: [{ type: 'url', message: '请输入有效的图片URL', trigger: 'blur' }]
}

// 表单引用
const formRef = ref()
const submitting = ref(false)

// 上传相关
const uploadModalVisible = ref(false)
const uploading = ref(false)
const fileList = ref([])
const imageUrl = ref('')
const selectedFile = ref<File | null>(null)

// 加载应用信息
const loadAppInfo = async () => {
  try {
    const response = isAdmin.value
      ? await getAppById({ id: appId.value })
      : await getAppById1({ id: appId.value })

    if (response.data.code === 200 && response.data.data) {
      Object.assign(appInfo, response.data.data)

      // 检查编辑权限
      if (!canEdit.value) {
        message.error('您没有权限编辑此应用')
        router.push('/')
        return
      }

      // 填充表单数据
      Object.assign(formData, {
        appName: appInfo.appName || '',
        cover: appInfo.cover || '',
        initPrompt: appInfo.initPrompt || '',
        codeGenType: appInfo.codeGenType || '',
        priority: appInfo.priority || 0
      })
    } else {
      message.error('获取应用信息失败')
      router.push('/')
    }
  } catch (error) {
    message.error('获取应用信息失败')
    console.error(error)
    router.push('/')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    const updateData = {
      id: appId.value,
      appName: formData.appName,
      cover: formData.cover
    }

    // 管理员可以更新优先级
    if (isAdmin.value) {
      Object.assign(updateData, { priority: formData.priority })
    }

    const response = isAdmin.value ? await updateApp(updateData) : await updateApp1(updateData)

    if (response.data.code === 200) {
      message.success('保存成功')
      // 重新加载应用信息
      await loadAppInfo()
    } else {
      message.error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error(error)
  } finally {
    submitting.value = false
  }
}

// 删除应用
const handleDelete = () => {
  if (!isAdmin.value) return

  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个应用吗？此操作不可恢复。',
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        const response = await deleteApp({ id: appId.value })
        if (response.data.code === 200) {
          message.success('删除成功')
          router.push('/admin/app-manager')
        } else {
          message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        message.error('删除失败')
        console.error(error)
      }
    }
  })
}

// 返回
const handleBack = () => {
  router.back()
}

// 上传封面
const handleUploadCover = () => {
  uploadModalVisible.value = true
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }

  // 保存选中的文件
  selectedFile.value = file
  return false // 阻止自动上传，我们手动处理
}

// 上传变化
const handleUploadChange = () => {
  // 由于我们在 beforeUpload 中阻止了自动上传，这里主要处理预览
  if (selectedFile.value) {
    getBase64(selectedFile.value, url => {
      imageUrl.value = url
    })
  }
}

// 提交上传
const handleUploadSubmit = async () => {
  if (!selectedFile.value) {
    message.warning('请先选择图片')
    return
  }

  uploading.value = true
  const loadingMessage = message.loading('正在上传封面...', 0)

  try {
    // 创建FormData对象，用于二进制文件上传
    const uploadFormData = new FormData()
    uploadFormData.append('image', selectedFile.value)

    // 调用上传接口
    const res = await uploadImage(uploadFormData, {
      headers: {
        // 不设置Content-Type，让浏览器自动设置multipart/form-data
      },
      data: uploadFormData
    })

    if (res.data.code === 200 && res.data.data) {
      // 上传成功，设置封面URL
      formData.cover = res.data.data
      uploadModalVisible.value = false
      imageUrl.value = ''
      selectedFile.value = null
      fileList.value = []
      message.success('封面上传成功')
    } else {
      message.error(res.data.message || '封面上传失败')
    }
  } catch (error) {
    console.error('封面上传失败：', error)
    message.error('封面上传失败，请重试')
  } finally {
    uploading.value = false
    loadingMessage()
  }
}

// 取消上传
const handleUploadCancel = () => {
  uploadModalVisible.value = false
  imageUrl.value = ''
  selectedFile.value = null
  fileList.value = []
}

// 获取base64
const getBase64 = (img: File, callback: (url: string) => void) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result as string))
  reader.readAsDataURL(img)
}

// 格式化时间
const formatTime = (timeStr?: string) => {
  if (!timeStr) return '未知'
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  loadAppInfo()
})
</script>

<style scoped>
.app-edit-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.page-header {
  margin-bottom: 24px;
}

.edit-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.edit-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.cover-upload {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.cover-preview {
  width: 200px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
  flex-shrink: 0;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  color: #999;
}

.cover-placeholder :deep(.anticon) {
  font-size: 32px;
  margin-bottom: 8px;
}

.cover-placeholder p {
  margin: 0;
  font-size: 12px;
}

.cover-input {
  flex: 1;
}

.form-help {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-details h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.user-details p {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 14px;
}

.cover-uploader {
  text-align: center;
}

.cover-uploader :deep(.ant-upload.ant-upload-select-picture-card) {
  width: 200px;
  height: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-edit-page {
    padding: 0 16px;
  }

  .cover-upload {
    flex-direction: column;
    gap: 16px;
  }

  .cover-preview {
    width: 100%;
    height: 150px;
  }

  .user-info {
    flex-direction: column;
    text-align: center;
  }
}
</style>
